import { delay } from '@/utils/common-tools'
import { formatDate } from '@/service/date'
import { fetchGoodsList, getAllGoodsCount } from '@/service/api'

let running = false
export default {
  namespaced: true,
  state: {
    /* 页数 */
    currentPage: 1,
    /* 查询关键字 */
    searchType: 'name',
    /* 查询内容 */
    searchName: '',
    /* 总数据数量 */
    totals: 0,
    /* 当前页数据 */
    currentData: []
  },
  mutations: {
    saveGoodsList(state, { result }) {
      state.currentData = result.map(v => ({
        ...v,
        updatetime: v.updatetime
          ? formatDate(new Date(v.updatetime), 'yyyy-MM-dd hh:mm:ss')
          : ''
      }))
    },
    updateTotals (state, { totals }) {
      if (totals) {
        state.totals = totals
      } else {
        state.totals -= 1
      }
    },
    /* 重置条件 */
    resetFilter(state) {
      state.searchName = ''
      state.totals = 0
      state.currentPage = 1
    },
    /* 更新页数 */
    updatePage(state, { currentPage }) {
      state.currentPage = currentPage
    },
    /* 更新删选条件 */
    updateFilter(state, { searchName, searchType }) {
      state.searchName = searchName
      state.searchType = searchType
      state.currentPage = 1
    }
  },
  actions: {
    /* 获取数据列表 */
    async fetchGoodsList({ state, commit }) {
      if (running) return
      running = true
      const { searchName, searchType, currentPage } = state
      const { data } = await fetchGoodsList({
        name: searchName,
        type: searchType,
        currentPage
      })
      await delay(100)
      running = false
      if (!data || +data.code !== 200) {
        return false
      }
      commit({
        type: 'saveGoodsList',
        result: data.result
      })
    },
    /* 获取数据总量 */
    async fetchGoodsCount({ state, commit }) {
      const { searchName, searchType } = state
      const { data } = await getAllGoodsCount({
        name: searchName,
        type: searchType
      })
      if (!data || +data.code !== 200) {
        return false
      }
      commit({
        type: 'updateTotals',
        totals: data.goodsCount
      })
    }
  }
}
